import SessionStorageComponent from "@runtime/module/SessionStorage/SessionStorageComponent";

/**
 * 应用设置
 */
export default class AppSettings implements Chaos.IDisposable {
    private static instance: AppSettings = new AppSettings();
    public static get Default(): AppSettings {
        return this.instance;
    }

    constructor() {
        window.addEventListener('beforeunload', this.OnBeforeUnload.bind(this));
        window.addEventListener('unload', this.Dispose.bind(this));

        if (SessionStorageComponent.Default.Contains('AppSettings')) {
            const settings = SessionStorageComponent.Default.ReadAs<AppSettings>('AppSettings');
            AppSettings.Copy(settings, this);
        }
    }

    /**
     * 刷新前
     */
    private OnBeforeUnload(): void {
        // 存储设置用于刷新时数据恢复
        SessionStorageComponent.Default.Add('AppSettings', AppSettings.Default);
    }

    Dispose() {
        window.removeEventListener('unload', this.Dispose);
    }

    /**
     * 本地地址
     */
    public LocalAddress: string = '';

    /**
     * 模式
     */
    public Mode: string = '';

    /**
     * 产品类型
     */
    public Type: string = '';

    /**
     * 产品Id
     */
    public Id: number = 0;

    /**
     * 产品简称
     * @description 用于定位当前产品相关配置
     */
    public ShortName: string = '';

    /**
     * 产品启动参数
     */
    public StartupParameter: Object = {};

    /**
     * 是否为开发者模式
     */
    public get IsDevelopment(): boolean {
        return this.Mode == 'Development';
    }

    /**
     * 将启动参数转换为目标类型
     * @param type 目标类型
     * @returns 目标类型实例
     */
    public static ReadStartupParameterAs<TSettings extends Object>(type: new () => TSettings): TSettings {
        return AppSettings.Default.StartupParameter as TSettings;
    }

    /**
     * 将源配置赋值到目标配置
     * @param source 源配置
     * @param destination 目标配置
     */
    public static Copy(source: AppSettings, destination: AppSettings): void {
        destination.LocalAddress = source.LocalAddress;
        destination.Mode = source.Mode;

        destination.Type = source.Type;
        destination.Id = source.Id;
        destination.ShortName = source.ShortName;
        destination.StartupParameter = source.StartupParameter;
    }
}